<?php

namespace App\Models\Common;

use App\Http\Traits\UsesUuid;
use App\Services\Com\LogService;
use Illuminate\Support\Facades\Route;
use WeSoonNet\LaravelPlus\Traits\Timezone;
use Illuminate\Database\Eloquent\Model;
use App\Services\Geographical\Geographical;
use Illuminate\Support\Facades\Cache;
class City extends Model
{
    use Geographical, Timezone;

    protected        $table        = 'com_cities';
    protected        $guarded      = ['created_at', 'updated_at'];
    protected        $hidden       = ['pivot'];
    public           $incrementing = false;
    protected static $kilometers   = true;
    protected        $casts        = [
        'created_at' => 'datetime:Y-m-d H:i:s',
        'updated_at' => 'datetime:Y-m-d H:i:s',
        'deleted_at' => 'datetime:Y-m-d H:i:s',
    ];

    public static function boot()
    {
        parent::boot();

        static::created(function ($model)
        {
            LogService::write('C', true, Route::currentRouteName(), json_encode($model->attributes), $model->table);
        });

        static::updated(function ($model)
        {
            // 对比更改
            $original = $model->getOriginal();
            $changes  = [];
            foreach ($model->getChanges() as $key => $value)
            {
                $changes[$key] = [
                    'old' => $original[$key],
                    'new' => $value,
                ];
            }
            LogService::write('U', true, Route::currentRouteName(), json_encode($changes), $model->table);
        });

        static::deleted(function ($model)
        {
            LogService::write('D', true, Route::currentRouteName(), json_encode($model->attributes), $model->table);
        });
    }

    const LATITUDE  = 'lat';
    const LONGITUDE = 'lng';

    static public function getSelfAndChildId($id)
    {
        if ($rows = static::select(['id'])->where('paths', 'like', "%{$id}%")->get())
        {
            return array_map(function ($item)
            {
                return $item['id'];
            }, $rows->toArray());
        }

        return [];
    }
    static public function getCityById($id)
    {
        $cache_key = config('cache.key_list.get_city_by_id').$id;
        $cache_data = Cache::get($cache_key);
        if(!empty($cache_data)){
            return $cache_data;
        }

        $rows = static::select(['path_names','parent_id','name','paths','is_city','level'])->where('id', '=', "$id")->first();
        
        if(empty($rows)){
            return null;
        }else{
            $res = $rows->toArray();
            Cache::put($cache_key, $res, config('cache.ttl_cfg'));
            return $res;
        }
    }

    static public function getCityByParentId($id)
    {
        if(empty($id)){
            return null;
        }
        
        $cache_key = config('cache.key_list.get_city_by_parent_id').$id;
        $cache_data = Cache::get($cache_key);
        if(!empty($cache_data)){
            return $cache_data;
        }

        $rows = static::select('*')->where('parent_id', '=', "$id")->get();
        $res = $rows->toArray();

        if(empty($res)){
            return null;
        }else{
            Cache::put($cache_key, $res, config('cache.ttl_cfg'));
            return $res;
        }
    }
}
